package com.itheima.algorithm.sort;

import com.itheima.utils.ArrayTools;

//冒泡排序  将数组从小到大排序
public class BubbleSortDemo {
    public static void main(String[] args) {
        int[] arr = ArrayTools.getRandomList(10);
        
        bubbleSort(arr);

       printArr(arr,"最终交换结果");
    }

    static void bubbleSort(int[] arr) {
        printArr(arr,"初始数组");
        int count = 0;
        //控制循环次数
        for (int j = 0; j < arr.length - 1 ; j++) {
            int counts = 0;
            //遍历排序
            // -1是为了避免数组越界
            //-j是为了避免重复比较浪费算力
            for (int i = 0; i < arr.length - 1 - j; i++) {
                if (arr[i] > arr[i + 1]){
                    arr[i] = arr[i] ^ arr[i + 1];
                    arr[i+1] = arr[i] ^ arr[i + 1];
                    arr[i] = arr[i] ^ arr[i + 1];
                }
                count++;
                counts++;
            }
            printArr(arr,"第" + (j+1) + "次排序结果");
            System.out.println("本次交换了" + counts + "次");
        }
        System.out.println("总共交换次数count = " + count);
    }

    static void printArr(int[] arr , String s){
        System.out.print(s + ":[");
        for (int i = 0; i < arr.length; i++) {
            if (i != arr.length-1)
                System.out.print(arr[i] + " ");
            else
                System.out.println(arr[i] + "]");
        }
    }

}
